<template>
  <el-form ref="form" :model="form" label-width="80px">
    <el-form-item label="*商品名称">
      <el-input style="width:200px;" v-model="form.goodsName"></el-input>
    </el-form-item>
    <el-form-item label="*商品分类">
      <el-select v-model="form.catCode" @change="getSubCatByCatId" placeholder="请选择">
        <el-option v-for="(item,index) in catList" :label="item.catName" :value="item.catCode" :key="index"></el-option>
      </el-select>
      <el-select v-model="form.subCateCode" @change="handleSubCateChange" placeholder="请选择">
        <el-option v-for="(item,index) in subCatList" :label="item.catName" :value="item.catCode" :key="index">
        </el-option>
      </el-select>
    </el-form-item>

    <!-- 品牌选择-->
    <el-form-item label="*品牌选择">
      <el-select v-model="form.brandCode" placeholder="品牌">
        <el-option v-for="(item,index) in brandList" :label="item.brandName" :value="item.brandCode" :key="index">
        </el-option>
      </el-select>
    </el-form-item>

    <!-- 属性组选择-->
    <el-form-item label="*属性组选择">
      <el-select v-model="form.groupName" @change="getAttrByGroup" placeholder="属性组">
        <el-option v-for="(item,index) in attrGroupList" :label="item.groupName" :value="item.groupName" :key="index">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item v-for="(attr,index) in attrList">
      <!-- 固定属性 -->
      <template v-if="attr.attrType==1">
        <span>{{attr.attrName}}（固定属性）</span>
        <el-select v-model="form.attr[index]" :placeholder="attr.attrName" :key="index">
          <el-option v-for="(option,index2) in attr.options" :label="option" :value="option" :key="index2+100">
          </el-option>
        </el-select>
      </template>

      <!-- 单选属性 -->
      <template v-if="attr.attrType==2">
        <span>{{attr.attrName}}(单选属性）</span>
        <el-select v-model="form.attr[index]" :placeholder="attr.attrName" :key="index">
          <el-option v-for="(option,index2) in attr.options" :label="option" :value="option" :key="index2+100">
          </el-option>
        </el-select>
      </template>

      <!-- 复选属性 -->
      <template v-if="attr.attrType==3">
        <span>{{attr.attrName}}(复选属性）</span>
        <el-select v-model="form.attr[index]" multiple :placeholder="attr.attrName">
          <el-option v-for="option,index in attr.options" :key="index" :label="option" :value="option">
          </el-option>
        </el-select>
      </template>

      <!-- 自定义属性 -->
      <template v-if="attr.attrType==4">
        <span>{{attr.attrName}}(自定义属性）</span>
        <el-select v-model="form.attr[index]" multiple :placeholder="attr.attrName">
          <el-option v-for="option,index in attr.options" :key="index" :label="option" :value="option">
          </el-option>
        </el-select>
      </template>
    </el-form-item>

    <!-- 仓库选择-->
    <el-form-item label="*仓库选择">
      <el-select @change="whChange" v-model="form.whCode" placeholder="仓库">
        <el-option v-for="(item,index) in whList" :label="item.whName" :value="item.whCode" :key="index"></el-option>
      </el-select>
    </el-form-item>

    <!-- 门店选择-->
    <el-form-item label="*门店选择">
      <el-select v-model="form.shopCode" placeholder="门店">
        <el-option v-for="(item,index) in shopList" :label="item.shopName" :value="item.shopCode" :key="index">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item lable="图片上传">
      <div>
        <div class="img-list">
          <div class="img-content" v-for="(item,index) in fileList" :key="index">
            <span>{{item.flat==1?"*":""}}{{ item.pictype }}</span>
            <el-upload class="avatar-uploader" action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="(file, fileList) => {changeUrl(file, fileList, index)}">
              <img v-if="item.url" :src="item.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <i @click="deleteFile(index)" v-if="item.url" class="addGoodsdeletei el-icon-delete"></i>
          </div>
        </div>
      </div>
    </el-form-item>

    <el-form-item>
      <el-row :gutter="20">
        <el-col :span="12"><span>是否可租</span>
          <el-switch active-value=1 inactive-value=0 v-model="form.isRentable"></el-switch>
        </el-col>
        <el-col :span="12"><span>是否可售</span>
          <el-switch active-value=1 inactive-value=0 v-model="form.isSalable"></el-switch>
        </el-col>
      </el-row>
    </el-form-item>

    <el-form-item label="*备注">
      <el-input id="goodsDesc" style="width:100%;" type="textarea" v-model="form.goodsDesc"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">立即创建</el-button>
      <el-button @click="useParentCloseDialog">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    name: "AddGoods",
    data() {
      return {
        // form数据
        // 应该是当前用户id
        inputUser: JSON.parse(localStorage.getItem("loginAccount")).accountId,

        //form数据
        form: {
          goodsName: '',
          inputUser: JSON.parse(localStorage.getItem("loginAccount")).accountId,
          modifyBy: JSON.parse(localStorage.getItem("loginAccount")).accountId,
          catCode: '',
          subCateCode: "",
          attr: [],
          goodsDesc: '',
          groupName: "",
          brandCode: "",
          whCode: "",
          shopCode: "",
          isRentable: "1",
          isSalable: "1"
        },

        //图片上传相关
        // fileList: [{
        //   name: "正面",
        //   flat: 1,
        //   url: ""
        // }, {
        //   name: "反面",
        //   flat: 0,
        //   url: ""
        // }],
        fileList: [],
        uploadFileList: [],
        dialogVisible: false,
        dialogImageUrl: "",

        // 模拟属性查询结果
        // attrList : [
        //   {groupCode:1,attrName:'颜色',attrType:2,options:['红','黑','灰']},
        //   {groupCode:2,attrName:'尺寸',attrType:2,options:["大","中","小"]}
        //   ],
        //属性组查询结果
        attrGroupList: [],
        // 属性查询结果
        attrList: [],

        // 全部大类
        // catList:[{catCode:1,catName:"手机"},{catCode:2,catName:"电脑"},{catCode:3,catName:"背包"},{catCode:16,catName:"球类"}],
        catList: [],
        // 根据大类获取小类
        subCatList: [],

        // 获取仓库列表
        // whList:[{whCode:1,whName:"仓库1"},{whCode:2,whName:"仓库2"},{whCode:4,whName:"仓库3"},{whCode:5,whName:"仓库5"}],
        whList: [],
        //模拟仓库对应门店列表
        shopList: [],

        brandList: [],


      }
    },
    methods: {
      handleRemove(file) {
        console.log(file);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleDownload(file) {
        console.log(file);
      },
      onSubmit() {
        // 检查必选数据是否都有（必选文件）
        console.log(this.form)
        for (let key in this.form) {
          if (this.form[key] == "" | this.form[key].length == 0) {
            alert("*必填数据不能为空")
            return
          }
        }
        console.log(this.fileList)
        for (let key in this.fileList) {
          if (this.fileList[key].url == "" && this.fileList[key].flat == 1) {
            alert("*必上传图片不能为空")
            return
          }
        }

        console.log(this.attrList)
        var newFormAttr = JSON.parse(JSON.stringify(this.attrList))
        for(let i =0;i<this.form.attr.length;i++){
          newFormAttr[i].options = this.form.attr[i]
        }
        console.log(newFormAttr)
        this.form.attr = JSON.stringify(newFormAttr)

        var up_file_dom = document.getElementsByClassName("el-upload__input")
        console.log(up_file_dom.length)
        let data = new FormData();
        for (let i = 0; i < up_file_dom.length; i++) {
          var file = up_file_dom[i].files[0]
          // 由于file对象 pictype 只有getter
          var newfile = new File([file], this.fileList[i].pictype, {
            type: "image/jpeg"
          });
          data.append("file", newfile)
        }

        for (let key in this.form) {
          data.append(key, this.form[key])
        }

        console.log(this.uploadFileList)
        this.$http({
          method: 'post',
          url: "http://localhost:8888/pawnGoods/addGoods",
          hearders: {
            'Content-Type': 'multipart/form-data;charset=UTF-8'
          },
          data: data
        }).then(resp => {
          this.form = {
          goodsName: '',
          inputUser: JSON.parse(localStorage.getItem("loginAccount")).accountId,
          modifyBy: JSON.parse(localStorage.getItem("loginAccount")).accountId,
          catCode: '',
          subCateCode: "",
          attr: [],
          goodsDesc: '',
          groupName: "",
          brandCode: "",
          whCode: "",
          shopCode: "",
          isRentable: "1",
          isSalable: "1",
        }
          this.useParentCloseDialog()
        })
      },
      changeUrl(file, fileList, index) {
        console.log(fileList)
        const isJPG = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
          return
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return
        }

        var blobUrl = URL.createObjectURL(file.raw);
        this.fileList[index].url = blobUrl
        console.log(this.fileList)
        this.form.isRentable = "0"
        this.form.isRentable = "1"
      },
      maxAlert() {
        alert("最多只能添加一张")
      },
      useParentCloseDialog() {
        this.$emit("closeDialog", false)
      },
      getAllCate() {
        this.$http.get("/pawnProductCat/getAllProductCat", {
          params: {}
        }).then(resp => {
          this.catList = resp.data.data.records
        })
      },
      getSubCatByCatId() {
        this.subCatList = []
        this.attrGroupList = []
        this.form.subCateCode = ""
        this.$http.get("/pawnProductCat/getXProductCatByD", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp => {
          this.subCatList = resp.data.data.records
          console.log(this.subCatList)
        })
        //获取属性
        this.$http.get("/pawnAttrGroup/getAllGroupName", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp => {
          this.attrGroupList = resp.data.data
        })
        //获取品牌
        this.$http.get("/pawnBrand/getBrandByCatCode", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp => {
          this.brandList = resp.data.data
        })
      },
      getAttrByGroup() {
        //清除input
        this.attrList = []
        this.form.attr =[]
        this.$http.get("/pawnAttrConf/getConfByGroupName", {
          params: {
            groupName: this.form.groupName
          }
        }).then(resp => {
          this.attrList = resp.data.data
          var _this = this
          for (let key in this.attrList) {
            console.log(this.attrList[key].options)
            this.attrList[key].options = JSON.parse(this.attrList[key].options)
            if (this.attrList[key].attrType == 2 && this.attrList[key].attrType == 4) {
              this.form.attr.push([])
            } else {
              this.form.attr.push("")
            }
          }
          console.log(this.attrList)
          console.log(this.form.attr)
        })
      },
      getAllWh() {
        this.$http.get("/pawnWarehouse/getAllwh", {
          params: {

          }
        }).then(resp => {
          console.log(resp.data.data)
          this.whList = resp.data.data
        })
      },
      handleSubCateChange() {
        for (let key in this.subCatList) {
          if (this.subCatList[key].catCode == this.form.subCateCode) {
            this.fileList = JSON.parse(this.subCatList[key].evalPicDef)
            for(let key2 in this.fileList){
              this.fileList[key2]['url'] = ""
            }
            console.log(this.fileList)
            return
          }
        }
      },
      whChange() {
        // 获取门店对应仓库
        this.$http.get("/pawnShopWhRel/getShopByWhCode", {
          params: {
            whCode: this.form.whCode,
          }
        }).then(resp => {
          this.shopList = resp.data.data
        })
      },
      deleteFile(index){
        this.fileList[index].url = ""
        this.form.isRentable = "0"
        this.form.isRentable = "1"
        console.log(this.fileList)
      }
    },
    props: ['addGoodsDialogVisible'],
    created() {
      this.getAllCate()
      this.getAllWh()
    }
  }
</script>

<style>
  .img-content {
    float: left;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  #goodsDesc {
    height: 100px;
  }
  .addGoodsdeletei{
    cursor: pointer;
  }
</style>
